<template>
    <el-container v-show="!ganterDialog">
        <el-main class="contain">
            <div>
                <!-- <div class="title">青海省中波中心台>调度令>办理</div> -->
                <el-row>
                    <el-col :span="24">
                        <el-steps :active="activeStep" align-center>
                            <el-step title="中心发起" />
                            <el-step title="中心审核" />
                            <el-step title="台站接收" />
                            <el-step title="调度令分配执行" />
                            <el-step title="执行监控" />
                            <el-step title="归档" />
                        </el-steps>
                    </el-col>

                    <el-collapse v-model="activeNames" class="elcollapse">
                        <el-collapse-item name="1" class="topcard">
                            <template #title>
                                <span class="headtitle">主要信息</span>
                            </template>
                            <!-- <el-card shadow="never" class="topcard"> -->
                            <el-form ref="ruleform" :model="formData" :rules="rules" label-width="80px" label-position="left" status-icon style="margin-left:20px;">

                                <div class="content">

                                    <div class="detail">
                                        <el-form-item label="发送单位" prop="authorValue">
                                            <el-select v-model="formData.authorValue" class="m-2" placeholder="" :disabled="activeStep>=1||readonly">
                                                <el-option v-for="item in Author" :key="item.value" :label="item.label" :value="item.value" />
                                            </el-select>
                                        </el-form-item>
                                    </div>

                                    <div class="detail">
                                        <el-form-item label="起草部门" prop="senderOrgvalue">

                                            <el-select v-model="formData.senderOrgvalue" class="m-2" placeholder="" :disabled="activeStep>=1||readonly">
                                                <el-option v-for="item in senderOrg" :key="item.value" :label="item.label" :value="item.value" />
                                            </el-select>
                                        </el-form-item>
                                    </div>

                                    <div class="detail">
                                        <el-form-item label="调度文号" prop="serrialInput">

                                            <el-input v-model="formData.serrialInput" class="m-2" placeholder="" :disabled="activeStep>=1||readonly" />
                                        </el-form-item>
                                    </div>

                                    <div class="detail">
                                        <el-form-item label="性质" prop="typeValue">

                                            <el-select v-model="formData.typeValue" class="m-2" placeholder="" :disabled="activeStep>=1||readonly">
                                                <el-option v-for="item in typeOption" :key="item.value" :label="item.label" :value="item.value" />
                                            </el-select>
                                        </el-form-item>
                                    </div>

                                    <div class="detail">
                                        <el-form-item label="填表人" prop="senderValue">
                                            <el-cascader v-model="formData.senderValue" class="m-2" :options="userOptions" :props="userProps" @change="cascaderChange('senderValue')" :show-all-levels="false" :disabled="true" style="padding-right: 20px;width:220px;" />
                                            <!-- <el-select v-model="formData.senderValue" class="m-2" placeholder="Select" :disabled="activeStep>=1||readonly">
                                                <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
                                            </el-select> -->
                                        </el-form-item>
                                    </div>
                                </div>

                                <div class="content">
                                    <div class="detail">
                                        <el-form-item label="审核人1" prop="auditor1Value">
                                            <!-- <el-cascader style="padding-right: 20px;width:220px;" v-model="formData.auditor1Value" class="m-2" :options="userOptions" :props="userProps" @change="cascaderChange('auditor1Value')" :show-all-levels="false" :disabled="activeStep>=1||readonly" /> -->
                                            <el-select v-model="formData.auditor1Value" class="m-2" placeholder="" :disabled="activeStep>=1||readonly">
                                                <el-option v-for="item in verifyuserList" :key="item.value" :label="item.label" :value="item.value" />
                                            </el-select>
                                        </el-form-item>
                                    </div>

                                    <div class="detail">
                                        <el-form-item label="审核人2">
                                            <!-- <el-cascader style="padding-right: 20px;width:220px;" v-model="formData.auditor2Value" class="m-2" :options="userOptions" :props="userProps" @change="cascaderChange('auditor2Value')" :show-all-levels="false" :disabled="activeStep>=1||readonly" /> -->
                                            <el-select v-model="formData.auditor2Value" class="m-2" placeholder="" :disabled="activeStep>=1||readonly">
                                                <el-option v-for="item in verifyuserList" :key="item.value" :label="item.label" :value="item.value" />
                                            </el-select>
                                        </el-form-item>
                                    </div>

                                    <div class="detail">
                                        <el-form-item label="签发人" prop="signValue">
                                            <!-- <el-cascader style="padding-right: 20px;width:220px;" v-model="formData.signValue" class="m-2" :options="userOptions" :props="userProps" @change="cascaderChange('signValue')" :show-all-levels="false" :disabled="activeStep>=1||readonly" /> -->
                                            <el-select v-model="formData.signValue" class="m-2" placeholder="" :disabled="activeStep>=1||readonly">
                                                <el-option v-for="item in verifyuserList" :key="item.value" :label="item.label" :value="item.value" />
                                            </el-select>
                                        </el-form-item>
                                    </div>

                                    <div class="detail">
                                        <el-form-item label="调度名称" prop="projectName">

                                            <el-input v-model="formData.projectName" class="m-2" placeholder="" :disabled="activeStep>=1||readonly" />
                                        </el-form-item>
                                    </div>

                                    <div class="detail">
                                        <el-form-item label="接收台站" prop="stationInput">

                                            <el-dropdown ref="dropdown1" trigger="click" @visible-change="stationDropdown" class="m-2" :disabled="activeStep>=1||readonly">
                                                <el-input v-model="formData.stationInput" placeholder="" :disabled="activeStep>=1||readonly">
                                                    <template #append>
                                                        <el-button>
                                                            <el-icon class="el-icon--right">
                                                                <el-icon-arrow-down />
                                                            </el-icon>
                                                        </el-button>
                                                    </template>
                                                </el-input>
                                                <template #dropdown>

                                                    <stations ref="stationsComp" @sendStations="getStations" @confirm='StationConfirm' :disabled="activeStep>=1||readonly"></stations>

                                                </template>
                                            </el-dropdown>
                                        </el-form-item>
                                    </div>
                                </div>

                                <div class=" content">

                                    <div class="detail_m">
                                        <el-form-item label="附件" prop="uploadInput">
                                            <el-upload :disabled="activeStep>=1||readonly" style="width:calc(100%  );display: flex;" :show-file-list="false" v-model:file-list="upfileList" :on-change="handleChange" :action="uploadAction" :on-success="onSuccess" :on-error="onError">
                                                <el-input :disabled="activeStep>=1||readonly" v-model="formData.uploadInput" placeholder="">
                                                    <template #append>
                                                        <el-button>上传</el-button>
                                                    </template>
                                                </el-input>
                                            </el-upload>
                                        </el-form-item>
                                        <div class="download">
                                            <el-button type="success" @click="download(formData.uploadInput)" link>{{ formData.uploadInput }}</el-button>
                                        </div>
                                    </div>

                                    <div class="detail_m">
                                        <el-form-item label="有效日期" prop="time">
                                            <el-date-picker :disabled="activeStep>=1||readonly" class="m-3" v-model="formData.time" type="datetimerange" range-separator="至" start-placeholder="Start date" end-placeholder="End date" />
                                        </el-form-item>
                                    </div>

                                </div>
                            </el-form>
                            <!-- </el-card> -->
                        </el-collapse-item>

                        <!-- <el-card shadow="never" header="播出计划" class="middlecard"> -->
                        <el-collapse-item title="播出计划" name="2" class="middlecard">
                            <template #title>
                                <span class="headtitle">播出计划</span>
                            </template>
                            <el-button type="primary" size="small" icon="el-icon-plus" v-if="!readonly" @click="openDialog('新增',null)" style="margin-left:20px;"> 新增</el-button>
                            <scTable ref="listTable" :apiObj="contentlist.apiObj" :params="contentlist.params" :height="500" row-key="ProjectID" :hideSetting="true" stripe style="margin-left:20px;">
                                <el-table-column type="selection" width="50"></el-table-column>
                                <el-table-column type="index" />
                                <el-table-column v-if="activeStep>=1" label="台站" prop="StationName" width="120"></el-table-column>
                                <el-table-column label="机号" prop="TransmitterNumber" width="80">
                                    <template #default="scope">
                                        <div v-if="scope.row.TransmitterNumber==undefined">自动(默认)</div>
                                        <div v-else-if="scope.row.TransmitterNumber==''||scope.row.TransmitterNumber=='0'">自动(默认)</div>
                                        <div v-else>{{ scope.row.TransmitterNumber }}</div>

                                    </template>
                                </el-table-column>
                                <el-table-column label="天线" prop="AnntenaNumber" width="80">
                                    <template #default="scope">
                                        <div v-if="scope.row.AnntenaNumber==undefined">自动(默认)</div>
                                        <div v-else-if="scope.row.AnntenaNumber==''||scope.row.AnntenaNumber=='0'">自动(默认)</div>
                                        <div v-else>{{ scope.row.AnntenaNumber }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="频率" prop="Frequency" width="80"></el-table-column>
                                <el-table-column label="功率" prop="Capacity" width="80">
                                    <template #default="scope">
                                        <div v-if="scope.row.Capacity==undefined">自动(默认)</div>
                                        <div v-else-if="scope.row.Capacity==''||scope.row.Capacity=='0'">自动(默认)</div>
                                        <div v-else>{{ scope.row.Capacity }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="保障级别" prop="Priority" width="80">
                                    <template #default="scope">
                                        <div v-if="scope.row.Priority==0">无级别</div>
                                        <div v-if="scope.row.Priority==1">一般</div>
                                        <div v-if="scope.row.Priority==2">重要</div>
                                        <div v-if="scope.row.Priority==3">优先</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="开始结束时间" prop="times" width="140">
                                    <template #default="scope">
                                        <div v-html="scope.row.times"></div>
                                    </template>
                                </el-table-column>
                                <!-- <el-table-column label="结束时间" prop="EndTime" width="80"></el-table-column> -->
                                <el-table-column label="重复方式" prop="RepeatType" width="80">
                                    <template #default="scope">
                                        <div v-if="scope.row.RepeatType==0">每天</div>
                                        <div v-if="scope.row.RepeatType==1">每周</div>
                                        <div v-if="scope.row.RepeatType==2">每月</div>
                                        <div v-if="scope.row.RepeatType==3">指定日期</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="重复的开始日期" prop="RepeatDateBegin" width="150">
                                    <template #default="scope">
                                        {{proxy.$TOOL.dateFormat(scope.row.RepeatDateBegin, 'yyyy-MM-dd')}}
                                    </template>
                                </el-table-column>
                                <el-table-column label="重复的结束日期" prop="RepeatDateEnd" width="150">
                                    <template #default="scope">
                                        {{proxy.$TOOL.dateFormat(scope.row.RepeatDateEnd, 'yyyy-MM-dd')}}
                                    </template>
                                </el-table-column>

                                <el-table-column label="重复周期" prop="repeatarry" width="100"></el-table-column>

                                <el-table-column label="直属台" prop="Directly" width="80">
                                    <template #default="scope">
                                        <div v-if="scope.row.Priority==0">否</div>
                                        <div v-if="scope.row.Priority==1">是</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" v-if="!readonly" fixed="right" align="left" width="220">
                                    <template #default="scope">
                                        <!-- <el-button plain size="small">查看</el-button> -->
                                        <el-button type="primary" plain size="small" @click="openDialog('编辑',scope)">编辑</el-button>
                                        <el-popconfirm title="确定删除吗？" @confirm="deleteRow(scope)">
                                            <template #reference>
                                                <el-button plain type="danger" size="small">删除</el-button>
                                            </template>
                                        </el-popconfirm>
                                    </template>
                                </el-table-column>
                                <template #bottomTemp>
                                    <el-button type="primary" size="small" @click="checkrunPic">查看运行图</el-button>
                                </template>
                            </scTable>
                        </el-collapse-item>
                        <!-- </el-card> -->
                        <!-- <el-card shadow="never" header="流程记录" class="endcard"> -->
                        <el-collapse-item title="流程记录" name="3" class="endcard">
                            <template #title>
                                <span class="headtitle">流程记录</span>
                            </template>
                            <el-timeline style="margin-left:20px;">
                                <el-timeline-item v-for="(item ,index) in flowData" :key="index" center placement="top">
                                    <el-card>
                                        <h4>{{index+1}}.{{item.SignTitle}}</h4>
                                        <div class="content">{{item.SignContent}}</div>
                                        <div class="sign">
                                            <div class="name">签名: {{item.User}} </div>
                                            <div class="time">日期: {{item.SignDate}}</div>
                                        </div>
                                    </el-card>
                                </el-timeline-item>

                            </el-timeline>
                        </el-collapse-item>
                        <!-- </el-card> -->
                    </el-collapse>
                </el-row>
            </div>
        </el-main>
        <el-footer class="elfooter">
            <div v-if="!readonly">
                <el-button type="primary" v-auth="'order.save'" size="small" @click="saveOrder">保存</el-button>
                <!-- <el-button v-auth="'order.submit'" type="primary" size="small" :disabled="inputData.WorkflowID!='1'" @click="buttonClick('submitClick')">提交</el-button> -->
                <el-popconfirm title="确定提交吗？" @confirm="buttonClick('submitClick')">
                    <template #reference>
                        <el-button v-auth="'order.submit'" type="primary" plain size="small" :disabled="inputData.WorkflowID!='1'">提交</el-button>
                    </template>
                </el-popconfirm>

                <el-button type="primary" v-auth="'order.verify'" :disabled="getifVeriy(inputData)" size="small" @click="buttonClick('verifyClick')">
                    <div v-if="inputData.currentVeriyuserType == undefined || inputData.currentVeriyuserType == 'sh'"> 审核</div>
                    <div v-else>审批</div>
                </el-button>
                <el-button type="primary" size="small" :disabled="inputData.ProjectID==-1" @click="buttonClick('msgClick')">催办</el-button>

                <el-popconfirm v-auth="'order.execute'" title="确定测试吗？" @confirm="buttonClick('testClick')">
                    <template #reference>
                        <el-button type="primary" :disabled="getifTest(inputData ,inputData.selectChildrenRow)" size="small">
                            <div v-if="inputData.selectChildrenRow == undefined"> 测试</div>
                            <div v-else-if="inputData.selectChildrenRow.testUser == undefined||inputData.selectChildrenRow.testUser ==''"> 测试</div>
                            <div v-else>已测试</div>
                        </el-button>
                    </template>
                </el-popconfirm>

                <el-popconfirm v-auth="'order.execute'" title="确定执行吗？" @confirm="buttonClick('executeClick')">
                    <template #reference>
                        <el-button type="primary" :disabled="getifExcute(inputData ,inputData.selectChildrenRow)" size="small">
                            <div v-if="inputData.selectChildrenRow == undefined"> 执行</div>
                            <div v-else-if="inputData.selectChildrenRow.executeUser == undefined||inputData.selectChildrenRow.executeUser ==''"> 执行</div>
                            <div v-else>已执行</div>
                        </el-button>

                    </template>
                </el-popconfirm>

                <el-button type="danger" v-auth="'order.terminate'" :disabled="inputData.ProjectID==-1||inputData.Closed=='1'" size="small" @click="buttonClick('stopClick')">中止</el-button>

            </div>
            <div v-if="verifyonly">
                <el-button type="primary" v-auth="'order.verify'" :disabled="inputData.ProjectID==-1||inputData.Closed=='1'||inputData.ProjectVerify=='1'||inputData.WorkflowID=='1'" size="small" @click="buttonClick('verifyClick')">审核</el-button>
                <el-button type="primary" size="small" :disabled="inputData.ProjectID==-1" @click="buttonClick('msgClick')">催办</el-button>
            </div>
            <el-button type="primary" plain size="small" @click="buttonClick('endSave')">返回</el-button>
        </el-footer>
    </el-container>
    <el-container v-show="ganterDialog">
        <ganter ref="ganterComp" @back="back"></ganter>
    </el-container>
    <el-dialog v-model="dialog" width="98%" :close-on-click-modal="false" top="10px" :title="dialogTtile" destroy-on-close>

        <add ref="addDialog" :stationsJson="stationsJson" @closeDialog="closeDialog" @sendNewrow="newRow" @fresh="freshList"></add>

    </el-dialog>
    <!-- <el-dialog v-model="ganterDialog" width="98%" :close-on-click-modal="false" top="10px" destroy-on-close>
        <ganter ref="ganterComp"></ganter>
    </el-dialog> -->
</template>
  <script setup>  
import { reactive, getCurrentInstance, onMounted, ref, defineProps, defineEmits, defineExpose, nextTick } from 'vue'
import config from "@/config"
import stations from './components/stations.vue'
import ganter from '../ganter/index.vue'
import add from './add.vue'
const { proxy } = getCurrentInstance()
const emit = defineEmits(['endSave', 'verifyClick', 'msgClick', 'executeClick', 'stopClick', 'submitClick'])
// const props = defineProps(['orderRow'])
// console.log(orderRow);

//#region 变量
//台站选择框
let dropdown1 = ref(null)
//上传地址
let uploadAction = ref(config.API_URL + '/upload/uploadFile')
let upfileList = reactive([])

let activeNames = ref(['1', '2', '3'])
//时间
let currenttime = new Date()
let newtime = new Date(new Date().setDate(new Date().getDate() + 30))

//表单对象  json  验证
let ruleform = ref({})
let formData = reactive({
    authorValue: '',//发送单位
    senderOrgvalue: '',//起草部门
    serrialInput: '',//调度文号
    typeValue: '',//性质 
    senderValue: '',//填表人
    auditor1Value: '',//审核人1
    auditor2Value: '',//审核人2
    signValue: '',//签发人
    projectName: '',//调度名称
    stationInput: '',//接收台站
    stationIds: '',//接收台站ID
    uploadInput: '',//上传文件
    time: [
        new Date(currenttime.getFullYear(), currenttime.getMonth(), currenttime.getDate(), currenttime.getHours(), 0, 0),
        new Date(newtime.getFullYear(), newtime.getMonth(), newtime.getDate(), newtime.getHours(), 0, 0),
    ],//时间
    startTime: '',//开始时间
    endTime: '',//结束时间
    contentData: [],//播出计划

})
let rules = reactive({
    authorValue: [
        { required: true, message: '请选择发送单位', trigger: 'change' }
    ],
    senderOrgvalue: [
        { required: true, message: '请选择起草部门', trigger: 'change' }
    ],
    serrialInput: [
        { required: true, message: '请填写调度文号', trigger: 'change' }
    ],
    typeValue: [
        { required: true, message: '请选择性质', trigger: 'change' }
    ],
    senderValue: [
        { required: true, message: '请填写填表人', trigger: 'change' }
    ],
    auditor1Value: [
        { required: true, message: '请选择审核人', trigger: 'change' }
    ],
    signValue: [
        { required: true, message: '请选择签发人', trigger: 'change' }
    ],
    projectName: [
        { required: true, message: '请填写调度名称', trigger: 'change' }
    ],
    stationInput: [
        { required: true, message: '请选择接收台站', trigger: 'change' }
    ],
    uploadInput: [
        { required: true, message: '请上传附件', trigger: 'change' }
    ],
    time: [
        { required: true, message: '请选择有效日期', trigger: 'change' }
    ],
})

//流程对象
let flowData = reactive([
    // {
    //     ProjectID: 0,
    //     FlowID: 0,
    //     User: 'admin',
    //     SignDate: '2022-10-11 00:00:00',
    //     SignTitle: '审核签名',
    //     SignContent: '同意'

    // }
])

//列表对象
let listTable = ref(null)

//台站选择组对象
let stationsComp = ref(null)
//台站选择组件json
let stationsJson = {}

//弹框对象
let addDialog = ref(null)
let dialog = ref(false)
let dialogTtile = ref('新增')

//甘特图
let ganterComp = ref(null)
let ganterDialog = ref(false)

//步骤
let activeStep = ref(0)

//列表查询接口和参数
let contentlist = ref({
    apiObj: proxy.$API.order.content,
    //搜索参数
    params: {
        ProjectID: -1,
        activeStep: 0,
        deptTtype: proxy.$TOOL.data.get("USER_INFO").deptTtype,
        deptId: proxy.$TOOL.data.get("USER_INFO").deptId,
        userId: proxy.$TOOL.data.get("USER_INFO").userId,//用户ID
    }
})
//传值进来的数据
let inputData = ref({})

//发送单位 
let Author = ref([
    {
        value: '中波中心',
        label: '中波中心',
    }
])
//起草部门 
let senderOrg = ref([
    {
        value: '技术处',
        label: '技术处',
    }
])

//性质 
let typeOption = ref([])
//用户列表
let userList = reactive([])
let verifyuserList = reactive([])
let userOptions = reactive([])
let userProps = {
    //expandTrigger: 'hover', 

}
//只读模式
let readonly = ref(false)
//审核模式
let verifyonly = ref(false)
//#endregion



//#region 方法

//判断当前账户下是否可以审核
let getifVeriy = (row) => {

    if (row.Closed == '1' || row.ProjectVerify == '1' || row.WorkflowID == '1')
        return true
    else {
        if (row.currentVeriyuserId == proxy.$TOOL.data.get("USER_INFO").userId)
            return false
        else
            return true
    }

}

//判断当前账户下点击可以执行
let getifExcute = (row, childrenrow) => {
    if (row.Closed == '1')
        return true
    else {

        if (row.ProjectVerify == '1') {//审核通过并且在第3步且已经被接收的才能点击执行按钮 && row.WorkflowID == '4'
            if (childrenrow == undefined)
                return true
            else {
                if (proxy.$TOOL.data.get("USER_INFO").deptTtype == '中心')

                    if (childrenrow.statue == '已接收') {

                        if ((childrenrow.executeUser == undefined || childrenrow.executeUser == '') && childrenrow.testUser != '')
                            return false
                        else
                            return true
                    }
                    else
                        return true

                else {
                    let result = false
                    if (childrenrow.stationID != undefined) {
                        if (childrenrow.stationID.toString() == proxy.$TOOL.data.get("USER_INFO").deptId.toString()) {
                            if (childrenrow.statue == '已接收') {
                                if ((childrenrow.executeUser == undefined || childrenrow.executeUser == '') && childrenrow.testUser != '')
                                    result = false
                                else
                                    result = true
                            }
                            else
                                return true
                        }
                        else
                            result = true


                        return result
                    }
                    else
                        return true
                }
            }



            // if (childrenrow.statue == '已接收')
            //     return false
            // else
            //     return true

        }
        else
            return true

    }

}

//判断当前账户下点击可以测试
let getifTest = (row, childrenrow) => {

    if (row.Closed == '1')
        return true
    else {

        if (row.ProjectVerify == '1') {//审核通过并且在第3步且已经被接收的才能点击按钮 
            if (childrenrow == undefined)
                return true
            else {
                if (proxy.$TOOL.data.get("USER_INFO").deptTtype == '中心')

                    if (childrenrow.statue == '已接收') {

                        if (childrenrow.testUser == undefined || childrenrow.testUser == '')
                            return false
                        else
                            return true
                    }
                    else
                        return true

                else {
                    let result = false
                    if (childrenrow.stationID != undefined) {
                        if (childrenrow.stationID.toString() == proxy.$TOOL.data.get("USER_INFO").deptId.toString()) {
                            if (childrenrow.statue == '已接收') {
                                if (childrenrow.testUser == undefined || childrenrow.testUser == '')
                                    result = false
                                else
                                    result = true
                            }
                            else
                                return true
                        }
                        else
                            result = true


                        return result
                    }
                    else
                        return true
                }
            }


        }
        else
            return true

    }

}

//台站选择确认事件
let StationConfirm = () => {
    dropdown1.value.handleClose()
}

//甘特图返回
let back = () => {
    ganterDialog.value = false
}

//列表刷新
let freshList = () => {
    listTable.value.refresh()
}

//用户级联组件选择事件
let cascaderChange = (key) => {
    formData[key] = formData[key][formData[key].length - 1]

}

//底部按钮事件
let buttonClick = (emitName) => {
    emit(emitName)
}

//上传
let handleChange = (uploadFile, uploadFiles) => {

}

//下载
let download = async (filename) => {
    let result = await proxy.$API.order.download.get({ filename: filename }, { responseType: 'blob' })//

    let reader = new FileReader()
    reader.readAsText(result, 'utf-g')

    reader.onload = () => {
        try {
            let json = JSON.parse(reader.result)

            if (json.code == 400)
                proxy.$alert(json.message, "异常", { type: 'error' })
            else
                downloadFile(result, filename)
        } catch (error) {
            downloadFile(result, filename)
        }
    }
}
let downloadFile = (blobdata, filename) => {

    let blob = new Blob([blobdata], { type: "application/octet-stream" })
    let blobURL = window.URL.createObjectURL(blob)
    let templink = document.createElement('a')
    templink.style.display = 'none'
    templink.href = blobURL
    templink.setAttribute('target', '_blank')
    templink.setAttribute('download', filename);
    document.body.appendChild(templink)
    templink.click()
    document.body.removeChild(templink)
    window.URL.revokeObjectURL(blobURL)

}

//上传成功
let onSuccess = (response, file, uploadFiles) => {
    formData.uploadInput = file.name

}
//上传失败
let onError = (error, file, uploadFiles) => {
    //formData.uploadInput = file.name
    proxy.$message.error(error.message)
}

//查看运行图
let checkrunPic = async () => {
    ganterDialog.value = true
    nextTick(async () => {
        let _obj = JSON.stringify(formData)
        let newdata = JSON.parse(_obj)

        newdata.deptTtype = proxy.$TOOL.data.get("USER_INFO").deptTtype
        newdata.StationID = proxy.$TOOL.data.get("USER_INFO").deptId
        let result = {}
        if (activeStep.value > 2) {
            result = await proxy.$API.order.plan.get(newdata)
        }
        else {
            let pram = {}
            Object.assign(pram, contentlist.value.params)
            pram.page = -1
            result = await proxy.$API.order.content.get(pram)
            if (result.code == 200) {
                for (var i = 0; i < result.data.rows.length; i++) {
                    result.data.rows[i].DataID = i
                    if (result.data.rows[i].TransmitterNumber == undefined) {
                        result.data.rows[i].TransmitterNumber = '自动(默认)'
                    }
                    else {
                        if (result.data.rows[i].TransmitterNumber.toString() == '0' || result.data.rows[i].TransmitterNumber == '')
                            result.data.rows[i].TransmitterNumber = '自动(默认)'
                    }
                    if (result.data.rows[i].AnntenaNumber == undefined)
                        result.data.rows[i].AnntenaNumber = '自动(默认)'
                    else {
                        if (result.data.rows[i].AnntenaNumber.toString() == '0' || result.data.rows[i].AnntenaNumber == '')
                            result.data.rows[i].AnntenaNumber = '自动(默认)'
                    }
                    if (result.data.rows[i].Capacity == undefined)
                        result.data.rows[i].Capacity = '自动(默认)'
                    else {
                        if (result.data.rows[i].Capacity.toString() == '0' || result.data.rows[i].Capacity == '')
                            result.data.rows[i].Capacity = '自动(默认)'
                    }
                }
            }
        }

        if (result.code == 200) {

            ganterComp.value.setData(result.data.rows)
        }
        else
            proxy.$alert(result.message, "异常", { type: 'error' })
    })
}

//调令保存
let saveOrder = async () => {

    ruleform.value.validate(async (valid) => {
        if (valid) {

            let _obj = JSON.stringify(formData)
            let newdata = JSON.parse(_obj)
            newdata.contentData = JSON.parse(JSON.stringify(listTable.value.tableData))

            newdata.startTime = proxy.$TOOL.dateFormat(newdata.time[0], 'yyyy-MM-dd hh:mm:ss')
            newdata.endTime = proxy.$TOOL.dateFormat(newdata.time[1], 'yyyy-MM-dd hh:mm:ss')
            newdata.activeStep = activeStep.value

            //判断此账号是否可编辑全部台站调度
            if (proxy.$TOOL.data.get("USER_INFO").deptTtype == '台站') {
                if (inputData.value.ProjectSender == proxy.$TOOL.data.get("USER_INFO").userId ||
                    inputData.value.ProjectAuditor == proxy.$TOOL.data.get("USER_INFO").userId ||
                    inputData.value.ProjectAuditor2 == proxy.$TOOL.data.get("USER_INFO").userId ||
                    inputData.value.ProjectSign == proxy.$TOOL.data.get("USER_INFO").userId)

                    newdata.ifeditall = true
                else
                    newdata.ifeditall = false
            }
            else
                newdata.ifeditall = true
            newdata.deptId = proxy.$TOOL.data.get("USER_INFO").deptId


            if (inputData.value.ProjectID == -1) {
                //新增
                let result = await proxy.$API.order.add.post(newdata)

                if (result.code == 200) {
                    inputData.value.ProjectID = result.ProjectID

                    proxy.$message.success("新增成功")
                    emit('endSave')
                }
                else
                    proxy.$alert(result.message, "异常", { type: 'error' })
            }
            else {
                //保存

                let result = await proxy.$API.order.update.post(newdata)
                if (result.code == 200) {
                    proxy.$message.success("保存成功")
                    emit('endSave')
                }
                else
                    proxy.$alert(result.message, "异常", { type: 'error' })
            }

        } else {
            proxy.$alert("请正确填写！", "提示", { type: 'error' })
            //this.$message.warn("请正确填写！")
            return false;
        }
    })


}

//页面重置
let pageRset = () => {
    document.documentElement.scrollTop = 0
    readonly.value = false
    ruleform.value.resetFields()

    stationsJson = {}
    stationsComp.value.resetStation()
    formData.senderValue = proxy.$TOOL.data.get("USER_INFO").userId

    formData.stationIds = ''
    formData.auditor2Value = ''
    listTable.value.upData({
        ProjectID: -1,
        activeStep: 0,
        deptTtype: proxy.$TOOL.data.get("USER_INFO").deptTtype,
        deptId: proxy.$TOOL.data.get("USER_INFO").deptId,
        userId: proxy.$TOOL.data.get("USER_INFO").userId,//用户ID
    })
    getFlow()

}

//关闭对话框
let closeDialog = () => {
    dialog.value = false
}

//新增一行
let newRow = (data, index) => {
    let _obj = JSON.stringify(data)
    let newrow = JSON.parse(_obj)

    let timesstring = ''
    if (newrow.StartTime1 != '' && newrow.EndTime1 != '' && newrow.EndTime1.substring(0, 8) != '00:00:00' && newrow.EndTime1 != '00:00:000')
        timesstring += '<div>' + newrow.StartTime1.substring(0, 8) + ' - ' + newrow.EndTime1.substring(0, 8) + '</div>'
    if (newrow.StartTime2 != '' && newrow.EndTime2 != '' && newrow.EndTime2.substring(0, 8) != '00:00:00' && newrow.EndTime1 != '00:00:000')
        timesstring += '<div>' + newrow.StartTime2.substring(0, 8) + ' - ' + newrow.EndTime2.substring(0, 8) + '</div>'

    if (newrow.StartTime3 != '' && newrow.EndTime3 != '' && newrow.EndTime3.substring(0, 8) != '00:00:0' && newrow.EndTime1 != '00:00:000')
        timesstring += '<div>' + newrow.StartTime3.substring(0, 8) + ' - ' + newrow.EndTime3.substring(0, 8) + '</div>'
    if (newrow.StartTime4 != '' && newrow.EndTime4 != '' && newrow.EndTime4.substring(0, 8) != '00:00:00' && newrow.EndTime1 != '00:00:000')
        timesstring += '<div>' + newrow.StartTime4.substring(0, 8) + ' - ' + newrow.EndTime4.substring(0, 8) + '</div>'
    if (newrow.StartTime5 != '' && newrow.EndTime5 != '' && newrow.EndTime5.substring(0, 8) != '00:00:00' && newrow.EndTime1 != '00:00:000')
        timesstring += '<div>' + newrow.StartTime5.substring(0, 8) + ' - ' + newrow.EndTime5.substring(0, 8) + '</div>'

    newrow.times = timesstring
    newrow.repeatarry = ''
    if (newrow.RepeatWeek != '')
        newrow.repeatarry = newrow.RepeatWeek
    else if (newrow.RepeatMonth != '')
        newrow.repeatarry = newrow.RepeatMonth
    else if (newrow.RepeatDateList != '')
        newrow.repeatarry = newrow.RepeatDateList

    if (activeStep.value >= 2) {
        newrow.StationName = newrow.stationInput
        newrow.StationID = newrow.StationIDs
    }

    if (index == -1) {
        newrow.ProjectID = formData.ProjectID
        newrow.ContentID = 0

        listTable.value.pushRow(newrow)
    }
    else {
        listTable.value.updateIndex(newrow, index)
    }

}

//删除行
let deleteRow = async (data) => {

    if (data.row.DataID != undefined) {
        let result = await proxy.$API.order.deletePlan.post(data.row)
        if (result.code == 200) {
            proxy.$message.success("删除成功")
            listTable.value.removeIndex(data.$index)
        }
        else
            proxy.$alert(result.message, "异常", { type: 'error' })
    }
    if (data.row.ContentID != undefined) {
        let result = await proxy.$API.order.deleteContent.post(data.row)
        if (result.code == 200) {
            proxy.$message.success("删除成功")
            listTable.value.removeIndex(data.$index)
        }
        else
            proxy.$alert(result.message, "异常", { type: 'error' })
    }

}

//台站选择下拉框
let stationDropdown = (value) => {
    if (value) {
        nextTick(() => {
            stationsComp.value.setStationvalue(stationsJson, formData.stationIds, formData.stationInput, true)
        })
    }

}

//打开新增编辑对话框
let openDialog = (text, scope) => {
    dialogTtile.value = text
    dialog.value = true
    nextTick(() => {

        if (text == '编辑') {
            scope.row.activeStep = activeStep.value

            if (activeStep.value >= 2)
                addDialog.value.setStationvalue(stationsJson, scope.row.StationID, scope.row.StationName, false)
            else
                addDialog.value.setStationvalue(stationsJson, formData.stationIds, formData.stationInput, true)
            addDialog.value.setPage(scope.row, scope.$index)
        }
        else {

            addDialog.value.setStationvalue(stationsJson, formData.stationIds, formData.stationInput, false)
            addDialog.value.setPage({
                activeStep: activeStep.value,
                ProjectID: inputData.value.ProjectID,
                senderValue: proxy.$TOOL.data.get("USER_INFO").userId,
                startTime: proxy.$TOOL.dateFormat(formData.time[0], 'yyyy-MM-dd hh:mm:ss'),
                endTime: proxy.$TOOL.dateFormat(formData.time[1], 'yyyy-MM-dd hh:mm:ss')
            }, -1, formData.stationInput)
        }

    })

}

//获取台站选择
let getStations = (labelstring, stationsjson, value) => {

    let _obj = JSON.stringify(stationsjson)
    stationsJson = JSON.parse(_obj)

    //stationsJson = stationsjson
    formData.stationInput = labelstring
    formData.stationIds = value
}

//赋值函数 
let setValue = async (orderRow) => {

    if (orderRow.ProjectID == undefined) {
        activeStep.value = 0;
        inputData.value = { ProjectID: -1 }
    }
    else {
        inputData.value = orderRow

        if (orderRow.ProjectID == -1) {

            activeStep.value = 0;
        }
        else {
            nextTick(() => {
                stationsComp.value.setStationvalue(stationsJson, orderRow.stationIds, '')
            })
            activeStep.value = orderRow.WorkflowID - 1;

            formData.authorValue = orderRow.ProjectAuthor//发送单位
            formData.senderOrgvalue = orderRow.ProjectSenderOrg//起草部门
            formData.serrialInput = orderRow.ProjectSerrial//调度文号

            formData.typeValue = orderRow.ProjectType.toString()//性质 
            formData.senderValue = Number(orderRow.ProjectSender)//填表人
            formData.auditor1Value = Number(orderRow.ProjectAuditor)//审核人1
            formData.auditor2Value = orderRow.ProjectAuditor2 == '' ? '' : Number(orderRow.ProjectAuditor2)//审核人2
            formData.signValue = Number(orderRow.ProjectSign)//签发人 
            formData.projectName = orderRow.ProjectName//调度名称

            //formData.stationInput = orderRow.ProjectAuthor//接收台站
            formData.stationIds = orderRow.stationIds//接收台站ID

            formData.uploadInput = orderRow.UploadFiles//上传文件
            formData.time = [
                new Date(orderRow.ProjectStartDate),
                new Date(orderRow.ProjectEndDate),
            ]//时间
            formData.startTime = orderRow.ProjectStartDate//开始时间
            formData.endTime = orderRow.ProjectEndDate//结束时间
            formData.ProjectID = orderRow.ProjectID
            formData.contentData = []


            //获取流程记录
            getFlow()

            let depts = await proxy.$API.system.dept.list.get()
            let inputstring = ''

            formData.stationIds.split(',').forEach(element => {

                depts.data.forEach(dept => {
                    dept.children.forEach(rate => {
                        if (rate.id.toString() == element)
                            inputstring += ',' + dept.label + '-' + rate.label
                    })
                })
            })

            formData.stationInput = inputstring == '' ? '' : inputstring.substring(1)


            if (orderRow.readonly != undefined)
                readonly.value = orderRow.readonly
            else
                readonly.value = false
            if (orderRow.verifyonly != undefined)
                verifyonly.value = orderRow.verifyonly
            else
                verifyonly.value = false

            //获取详表
            contentlist.value.params.ProjectID = orderRow.ProjectID
            contentlist.value.params.activeStep = activeStep.value
            console.log('ck', contentlist.value.params);
            listTable.value.upData(contentlist.value.params)
        }
    }
    if (inputData.value.ProjectID == -1) {
        activeNames.value = ['1']
    }
    else
        activeNames.value = ['1', '2', '3']
}

//获取流程记录
let getFlow = async () => {
    if (inputData.value.ProjectID != undefined) {
        if (inputData.value.ProjectID > 0) {
            let result = await proxy.$API.order.flowlist.post({ ProjectID: inputData.value.ProjectID })

            if (result.code == 200) {
                flowData.length = 0
                flowData.push(...result.data)
            }

        }
        else
            flowData.length = 0
    }
    else
        flowData.length = 0
}

//初始化
onMounted(async () => {

    pageRset()

    if (inputData.value == undefined) {
        activeStep.value = 0;
        inputData.value = { ProjectID: -1 }
    }
    else {
        if (inputData.value.ProjectID == undefined) {
            activeStep.value = 0;
            inputData.value = { ProjectID: -1 }
        }
    }

    if (inputData.value.ProjectID == -1) {
        activeNames.value = ['1']
    }
    else
        activeNames.value = ['1', '2', '3']



    let dept = await proxy.$API.system.dept.list.get()

    let user = await proxy.$API.system.user.all.get()
    userList.push(...user.data)
    let verifyusers = userList.filter(row => row.alias == 'Reviewer')
    verifyuserList.push(...verifyusers)

    let usertree = await proxy.$API.system.user.tree.get()

    userOptions.push(...usertree.data)

    getFlow()

    let ordertype = await proxy.$API.system.dic.listBycode.get({ code: 'ProjectType' })

    ordertype.data.rows.forEach(element => {
        typeOption.value.push({
            value: element.key,
            label: element.name,
        })
    });

})

//#endregion

//暴露的方法函数
defineExpose({ setValue, pageRset, getFlow })
</script>
<style lang="scss" scoped>
.contain {
    //margin: 14px;
    //overflow-y: hidden;
    .title {
        color: green;
        padding: 10px;
    }
}
.elcollapse {
    width: 100%;
    margin-top: 10px;

    .topcard {
        width: 100%;
        margin-top: 10px;

        .content {
            width: 100%;
            display: flex;
            flex-direction: row;
            //padding-bottom: 10px;
            .detail {
                width: 20%;
                display: flex;
                flex-direction: row;
                align-items: center;
                .m-2 {
                    padding-right: 20px;
                    width: 220px;
                }
            }
            .detail_m {
                width: 40%;
                display: flex;
                flex-direction: row;
                align-items: center;

                .m-3 {
                    padding-right: 20px;
                    width: calc(100% - 5vh);
                }
                .download {
                    width: 150px;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    height: 100%;
                    padding-top: 8px;
                    padding-left: 8px;
                }
            }
        }
    }
    .middlecard {
        width: 100%;
        margin-top: 10px;
    }
    .endcard {
        width: 100%;
        margin-top: 10px;

        .content {
            margin: 12px;
        }
        .sign {
            padding-top: 10px;
            display: flex;
            justify-content: flex-end;
            .name {
                width: 150px;
            }
            .time {
                width: 200px;
            }
        }
    }
}
.headtitle {
    font-size: 17px;
    font-weight: bold;
    padding: 15px 20px 20px 20px;
}

.elfooter {
    display: flex;
    justify-content: center;
    button {
        margin-right: 20px;
    }
}
</style>